package com.mmall.util;

import com.mmall.common.RedisPool;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;

public class RedisPoolUtil {

    private final static Logger logger = LoggerFactory.getLogger(RedisPoolUtil.class);

    public static String set(String key, String value) {
        Jedis jedis = null;
        String result = null;
        try {
            jedis = RedisPool.getJedis();
            jedis.set(key, value);
        } catch (Exception e) {
            logger.error("set key:{} value:{},error", key, value, e);
            RedisPool.returnBrokenResourse(jedis);
            return result;
        }
        RedisPool.returnResourse(jedis);
        return result;
    }

    public static String get(String key) {
        Jedis jedis = null;
        String result = null;
        try {
            jedis = RedisPool.getJedis();
            result = jedis.get(key);
        } catch (Exception e) {
            logger.error("get key:{},error", key, e);
            RedisPool.returnBrokenResourse(jedis);
            return result;
        }
        RedisPool.returnResourse(jedis);
        return result;
    }

    //set时加设置过期时间，且时间为秒
    public static String setex(String key, String value, int exTime) {
        Jedis jedis = null;
        String result = null;
        try {
            jedis = RedisPool.getJedis();
            jedis.setex(key, exTime, value);
        } catch (Exception e) {
            logger.error("setex key:{} seconds:{} value:{},error", key, value, e);
            RedisPool.returnBrokenResourse(jedis);
            return result;
        }
        RedisPool.returnResourse(jedis);
        return result;
    }

    //设置key的有效期
    public static Long expire(String key, int exTime) {
        Jedis jedis = null;
        Long result = null;
        try {
            jedis = RedisPool.getJedis();
            jedis.expire(key, exTime);
        } catch (Exception e) {
            logger.error("expire key:{} seconds:{},error", key, e);
            RedisPool.returnBrokenResourse(jedis);
            return result;
        }
        RedisPool.returnResourse(jedis);
        return result;
    }

    public static Long del(String key) {
        Jedis jedis = null;
        Long result = null;
        try {
            jedis = RedisPool.getJedis();
            jedis.del(key);
        } catch (Exception e) {
            logger.error("del key:{},error", key, e);
            RedisPool.returnBrokenResourse(jedis);
            return result;
        }
        RedisPool.returnResourse(jedis);
        return result;
    }

    public static void main(String[] args) {
        Jedis jedis = RedisPool.getJedis();
        System.out.println("--------");
        RedisPoolUtil.set("3", "ccc");
        String s = RedisPoolUtil.get("3");
        System.out.println(s);
        RedisPoolUtil.setex("4", "ccc", 60 * 5);
        RedisPoolUtil.expire("3", 60 * 3);
        RedisPoolUtil.del("4");
    }
}
